package com.totoro.service.impl;

import com.totoro.pojo.MyHistory;
import com.totoro.pojo.User;
import com.totoro.mapper.UserMapper;
import com.totoro.pojo.UserOnline;
import com.totoro.service.UserService;
import com.totoro.utils.MapSort;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author TOTORO
 * @date 2021/4/29 17:04
 * 用户service接口实现类
 */
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> findAllUser() {
        return userMapper.findAllUser();
    }

    @Override
    public User findUserById(int uid) {
        return userMapper.findUserById(uid);
    }

    @Override
    public List<User> userNameTest(String name) {
        return userMapper.userNameTest(name);
    }

    @Override
    public int addUser(User user) {
        return userMapper.addUser(user);
    }

    @Override
    public List<User> userInfoToPhone(String phone) {
        return userMapper.userInfoToPhone(phone);
    }

    @Override
    public User checkUser(String value) {
        return userMapper.checkUser(value);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public int updatePassword(String value, String password, String salt) {
        return userMapper.updatePassword(value, password, salt);
    }

    @Override
    public User findUser(int uid) {
        return userMapper.findUser(uid);
    }

    @Override
    public String saveUserDataByUid(MultipartFile file, User user, HttpServletRequest request, HttpSession session) throws IOException {

        User sessionUser = (User) session.getAttribute("user");
        // 需要拿到最新的头像，不能市session里的
        String nowHead = findUser(sessionUser.getUserId()).getHead();
        String uploadPath = request.getSession().getServletContext().getRealPath("/")+"static\\img\\user\\";

        // 保存图片的路径，图片上传成功后，将路径保存到数据库
        // 获取原始图片的扩展名
        String originalFilename = file.getOriginalFilename();
        // 生成文件新的名字
        String newFileName = UUID.randomUUID() + originalFilename;

        // 判断用户是否选择了头像
        if(originalFilename.length() > 0){
            // 删除之前的头像图片 （1）
            File afterHeadFile = new File(uploadPath+nowHead);
            if(afterHeadFile.exists()){
                afterHeadFile.delete();
            }

            // 封装上传文件位置的全路径
            File targetFile = new File(uploadPath, newFileName);
            file.transferTo(targetFile);
            user.setHead("\\static\\img\\user\\"+newFileName);
        }

        // 设置一些属性
        user.setUserId(sessionUser.getUserId());
        // 保存到数据库
        userMapper.saveUserDataByUid(user);
        return "redirect:/user/myData.htm";
    }

    @Override
    public Map<String, List<MyHistory>> findUserHistory(int uid) {
        List<MyHistory> myHistories = userMapper.findUserHistory(uid);
        for (MyHistory myHistory : myHistories) {
            System.out.println(myHistory.getCreateTime());
        }
        // 格式化日期
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        myHistories.forEach(v-> {
            try {
                v.setCreateTime(simpleDateFormat.format(simpleDateFormat.parse(v.getCreateTime())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        });
        List<MyHistory> newMyHistories = myHistories.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getCreateTime()))), ArrayList::new));

        Map<String, List<MyHistory>> map = new TreeMap<>();
        for (MyHistory newMyHistory : newMyHistories) {
            map.put(newMyHistory.getCreateTime(), new ArrayList<>());
        }
        map.forEach((k,v)->{
            for (MyHistory myHistory : myHistories) {
                System.out.println(k.equals(myHistory.getCreateTime()));
                if(k.equals(myHistory.getCreateTime())){
                    map.get(k).add(myHistory);
                }
            }
        });
        return MapSort.sortByKey(map, true);
    }

    @Override
    public Integer addMyHistory(MyHistory myHistory) {
        return userMapper.addMyHistory(myHistory);
    }

    @Override
    public MyHistory repeatHistory(int uid, int pid) {
        return userMapper.repeatHistory(uid,pid);
    }

    @Override
    public Integer deleteHistory(int mhId) {
        return userMapper.deleteHistory(mhId);
    }

    @Override
    public Integer addUserOnlineCount(int uid) {
        return userMapper.addUserOnlineCount(uid);
    }

    @Override
    public UserOnline findDayUserOnline(UserOnline userOnline) {
        return userMapper.findDayUserOnline(userOnline);
    }

    @Override
    public Integer addUserScore(int uid, int score) {
        return userMapper.addUserScore(uid, score);
    }

    @Override
    public Integer deleteUser(int uid) {
        return userMapper.deleteUser(uid);
    }

    @Override
    public Integer untieUserBan(int uid) {
        return userMapper.untieUserBan(uid);
    }
}
